<template>
  <div class="group-management-container">
    <!-- Action Bar -->
    <div class="action-bar-card">
      <el-button type="primary" @click="openCreateDialog">新建分组</el-button>
      <el-button type="danger" :disabled="selectedGroups.length === 0" @click="deleteSelectedGroups">删除分组</el-button>
      <el-input v-model="searchQuery" placeholder="搜索分组..." class="search-input" clearable><template #prefix><el-icon><Search /></el-icon></template></el-input>
    </div>

    <!-- Table Wrapper with Loading State -->
    <div class="table-wrapper">
      <div v-if="isLoading" class="loading-placeholder">正在加载数据...</div>
      <el-table v-else :data="paginatedData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="序号" width="80" align="center" />
        <el-table-column prop="name" label="分组名称" width="220" class-name="group-name-column" />
        <el-table-column label="成员">
          <template #default="{ row }">
            <div v-if="Array.isArray(row.members) && row.members.length > 0" class="member-list">
              <span v-for="(member, idx) in row.members.slice(0, 3)" :key="member.id">
                {{ member.name }}<span v-if="idx < row.members.slice(0, 3).length - 1">、</span>
              </span>
              <span v-if="row.members.length > 3">...</span>
            </div>
            <div v-else>无成员</div>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建者" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <span :class="['status-tag', row.status === '正常' ? 'status-enabled' : 'status-disabled']">{{ row.status }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <!-- 【新增】查看按钮 -->
            <el-button size="small" class="action-button action-edit" @click="openViewDialog(row)">查看</el-button>
            <!-- 状态切换按钮 -->
            <el-button size="small" class="action-button" :class="row.status === '正常' ? 'action-disable' : 'action-enable'" @click="toggleGroupStatus(row)">
              {{ row.status === '正常' ? '禁用' : '正常' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- Pagination -->
    <div class="pagination-container">
      <span class="pagination-summary">显示第 {{ (currentPage - 1) * pageSize + 1 }} 到 {{ Math.min(currentPage * pageSize, filteredGroups.length) }} 条，共 {{ filteredGroups.length }} 条记录</span>
      <el-pagination background layout="prev, pager, next" :total="filteredGroups.length" :page-size="pageSize" v-model:current-page="currentPage"/>
    </div>

    <!-- Create Dialog -->
    <el-dialog v-model="createDialogVisible" title="创建新分组" width="600px" :before-close="closeDialog">
      <!-- ... create dialog content remains the same ... -->
       <div class="create-group-dialog">
        <div class="form-item"><h3>分组名称</h3><el-input v-model="newGroup.name" placeholder="请输入分组名称" clearable /></div>
        <div class="form-item">
          <h3>选择成员</h3>
          <div class="selection-container">
            <div class="selection-panel">
              <h4>可选成员</h4>
              <el-input v-model="memberSearch" placeholder="搜索成员..." clearable class="search-box" />
              <div class="option-list"><el-checkbox-group v-model="newGroup.selectedMembers"><el-checkbox v-for="member in filteredMembers" :key="member.id" :label="member.id" class="option-item">{{ member.name }}（{{ member.department }}）</el-checkbox></el-checkbox-group></div>
            </div>
            <div class="selection-panel">
              <h4>已选成员</h4>
              <div class="selected-list">
                <div v-if="newGroup.selectedMembers.length === 0" class="empty-hint">未选择成员</div>
                <div v-for="memberId in newGroup.selectedMembers" :key="memberId" class="selected-item">{{ getMemberName(memberId) }}<el-icon class="remove-icon" @click="removeMember(memberId)"><Close /></el-icon></div>
              </div>
            </div>
          </div>
        </div>
        <div class="form-item">
          <h3>选择子分组</h3>
          <div class="selection-container">
            <div class="selection-panel">
              <h4>可选分组</h4>
              <el-input v-model="groupSearch" placeholder="搜索分组..." clearable class="search-box" />
              <div class="option-list"><el-checkbox-group v-model="newGroup.selectedSubGroups"><el-checkbox v-for="group in filteredSubGroups" :key="group.id" :label="group.id" class="option-item">{{ group.name }}</el-checkbox></el-checkbox-group></div>
            </div>
            <div class="selection-panel">
              <h4>已选子分组</h4>
              <div class="selected-list">
                <div v-if="newGroup.selectedSubGroups.length === 0" class="empty-hint">未选择子分组</div>
                <div v-for="groupId in newGroup.selectedSubGroups" :key="groupId" class="selected-item">{{ getGroupName(groupId) }}<el-icon class="remove-icon" @click="removeSubGroup(groupId)"><Close /></el-icon></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="saveGroup">创建</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 【新增】查看分组信息对话框 -->
    <el-dialog v-model="viewDialogVisible" :title="'查看分组：' + (viewingGroup ? viewingGroup.name : '')" width="600px" :before-close="closeViewDialog">
      <div v-if="viewingGroup" class="view-group-dialog">
        <div class="view-item">
          <span class="view-label">分组名称：</span>
          <span class="view-content">{{ viewingGroup.name }}</span>
        </div>
        <div class="view-item">
          <span class="view-label">创建者：</span>
          <span class="view-content">{{ viewingGroup.creator }}</span>
        </div>
        <div class="view-item">
          <span class="view-label">创建时间：</span>
          <span class="view-content">{{ viewingGroup.createTime }}</span>
        </div>
        <div class="view-item">
          <span class="view-label">状态：</span>
          <span class="view-content">
            <span :class="['status-tag', viewingGroup.status === '正常' ? 'status-enabled' : 'status-disabled']">{{ viewingGroup.status }}</span>
          </span>
        </div>
        <div class="view-item view-item-vertical">
          <span class="view-label">小组成员 ({{ viewingGroup.members.length }}人)：</span>
          <div class="view-member-list">
            <div v-if="viewingGroup.members.length > 0">
              <span v-for="(member, index) in viewingGroup.members" :key="member.id" class="member-tag">
                {{ member.name }}{{ index < viewingGroup.members.length - 1 ? '、' : '' }}
              </span>
            </div>
            <div v-else class="empty-hint">该分组下无成员</div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="closeViewDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Close } from '@element-plus/icons-vue';
import groupAPI from '@/api/Group.js';

import {
  logCreateGroupSuccess,
  logCreateGroupFailure,
  logDeleteGroupsSuccess,
  logDeleteGroupsFailure
} from '@/api/log.js';

export default {
  name: 'GroupManagement',
  components: { Search, Close },
  data() {
    return {
      isLoading: true,
      groups: [],
      allMembers: [],
      createDialogVisible: false,
      isEditMode: false,
      currentPage: 1,
      pageSize: 8,
      searchQuery: '',
      memberSearch: '',
      groupSearch: '',
      selectedGroups: [],
      newGroup: { id: null, name: '', selectedMembers: [], selectedSubGroups: [] },
      // 【新增】用于查看功能的 data
      viewDialogVisible: false,
      viewingGroup: null,
    };
  },
  computed: {
    filteredGroups() {
      if (!this.searchQuery) return this.groups;
      return this.groups.filter(g => (g.name && g.name.toLowerCase().includes(this.searchQuery.toLowerCase())) || (g.creator && g.creator.toLowerCase().includes(this.searchQuery.toLowerCase())));
    },
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredGroups.slice(start, end);
    },
    filteredMembers() {
      if (!this.memberSearch) return this.allMembers;
      return this.allMembers.filter(m => (m.name && m.name.includes(this.memberSearch)) || (m.department && m.department.includes(this.memberSearch)));
    },
    filteredSubGroups() {
      if (!this.groupSearch) return this.groups;
      return this.groups.filter(g => g.name.includes(this.groupSearch));
    },
  },
  methods: {
    async loadAndShowData() {
      this.isLoading = true;
      try {
        const [groupsRes, usersRes] = await Promise.all([groupAPI.getAllGroups(), groupAPI.getAllUsers()]);
        this.groups = groupsRes.data.map(g => ({ id: g.groupId, name: g.groupName, creator: g.userName, createTime: g.createTime, status: g.status, members: g.memberList ? g.memberList.map(u => ({ id: u.userId, name: u.name })) : [] }));
        this.allMembers = usersRes.data.map(u => ({ id: u.userId, name: u.name, department: u.department || '未知部门' }));
      } catch (error) {
        ElMessage.error('数据加载失败，请刷新页面。');
        console.error("加载数据时出错:", error);
      } finally {
        this.isLoading = false;
      }
    },
    async saveGroup() {
      if (!this.newGroup.name.trim()) {
        ElMessage.warning('请输入分组名称');
        return;
      }
      const finalMemberIdSet = new Set(this.newGroup.selectedMembers);
      if (this.newGroup.selectedSubGroups && this.newGroup.selectedSubGroups.length > 0) {
        try {
          const response = await groupAPI.searchUsersByGroupIds(this.newGroup.selectedSubGroups);
          const userList = response.data;
          if (userList && Array.isArray(userList)) {
            userList.forEach(user => { finalMemberIdSet.add(user.userId); });
          } else {
            console.warn('API返回的结果不是一个有效的数组！');
          }
        } catch (error) {
          ElMessage.error('获取子组成员信息失败，请重试！');
          console.error("获取子组成员时出错:", error);
          return;
        }
      }
      const finalMemberList = Array.from(finalMemberIdSet).map(memberId => {
        const memberInfo = this.allMembers.find(m => m.id === memberId);
        return { userId: memberInfo ? memberInfo.id : memberId, name: memberInfo ? memberInfo.name : '未知用户' };
      });
      // const userInfoStr = sessionStorage.getItem('userInfo');
      const userInfoStr = localStorage.getItem('userInfo');
      if (!userInfoStr) {
          ElMessage.error('无法获取用户信息，请重新登录！');
          return;
      }
      const currentUser = JSON.parse(userInfoStr);
      console.log('成功获取到缓存的用户信息:', currentUser);
      const payload = {
        groupName: this.newGroup.name,
        userId: currentUser.userId,
        userName: currentUser.name,
        // userName: currentUser.userName,
        status: '正常',
        memberList: finalMemberList,
      };
      try {
        await groupAPI.addGroup(payload);
        ElMessage.success('分组创建成功');

         logCreateGroupSuccess(payload.groupName); // ✅ 记录成功日志

        this.closeDialog();
        await this.loadAndShowData();
      } catch (error) {
        ElMessage.error('创建分组失败，请检查后端服务。');
        console.error("创建分组时出错:", error);

         logCreateGroupFailure(payload.groupName); // ✅ 记录失败日志
      }
    },
    async toggleGroupStatus(group) {
      const newStatus = group.status === '正常' ? '禁用' : '正常';
      try {
        await groupAPI.updateGroupStatus(group.id, newStatus);
        group.status = newStatus;
        ElMessage.success(`状态已更新为: ${newStatus}`);
      } catch (error) {
        ElMessage.error('状态更新失败！');
        console.error('toggleGroupStatus failed:', error);
      }
    },
    async deleteSelectedGroups() {
      if (this.selectedGroups.length === 0) {
        ElMessage.warning('请至少选择一个要删除的分组');
        return;
      }
      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${this.selectedGroups.length} 个分组吗？此操作不可逆。`,
          '警告',
          { confirmButtonText: '确定删除', cancelButtonText: '取消', type: 'warning' }
        );
        const groupIdsToDelete = this.selectedGroups.map(group => group.id);
         const groupNamesToDelete = this.selectedGroups.map(group => group.name); // 👈 提取名称用于日志
        try {
          await groupAPI.deleteGroups(groupIdsToDelete);
          ElMessage.success('分组已成功删除');

             logDeleteGroupsSuccess(groupNamesToDelete); // ✅ 记录成功日志

          await this.loadAndShowData();
          this.selectedGroups = [];
        } catch (error) {
          ElMessage.error('删除分组失败，请检查网络或联系管理员。');
          console.error("删除分组时出错:", error);
            logDeleteGroupsFailure(); // ✅ 记录失败日志
        }
      } catch (cancel) {
        ElMessage.info('已取消删除操作');
      }
    },
    openCreateDialog() {
      this.isEditMode = false;
      this.newGroup = { id: null, name: '', selectedMembers: [], selectedSubGroups: [] };
      this.memberSearch = '';
      this.groupSearch = '';
      this.createDialogVisible = true;
    },
    closeDialog() { this.createDialogVisible = false; },

    // 【新增】打开和关闭查看对话框的方法
    openViewDialog(group) {
      this.viewingGroup = group;
      this.viewDialogVisible = true;
    },
    closeViewDialog() {
      this.viewDialogVisible = false;
      this.viewingGroup = null;
    },

    handleSelectionChange(selection) { this.selectedGroups = selection; },
    getMemberName(id) {
      const member = this.allMembers.find(m => m.id === id);
      return member ? `${member.name}（${member.department}）` : `未知成员(ID:${id})`;
    },
    getGroupName(id) {
      const group = this.groups.find(g => g.id === id);
      return group ? group.name : '';
    },
    removeMember(id) { this.newGroup.selectedMembers = this.newGroup.selectedMembers.filter(mId => mId !== id); },
    removeSubGroup(id) { this.newGroup.selectedSubGroups = this.newGroup.selectedSubGroups.filter(gId => gId !== id); },
    editGroup(group) { ElMessage.info(`编辑功能待实现`); },
  },
  created() {
    // const mockUser = { userId: '10000001', userName: '刘博文' };
    // sessionStorage.setItem('userInfo', JSON.stringify(mockUser));
    this.loadAndShowData();
  }
}
</script>

<style scoped>
/* 所有样式保持原样 */
.group-management-container { padding: 20px; background-color: #f0f2f5; }
.action-bar-card { display: flex; gap: 12px; padding: 20px; margin-bottom: 20px; background-color: #fff; border-radius: 4px; }
.search-input { width: 300px; margin-left: auto; }
.table-wrapper { padding: 1px 20px 20px 20px; background-color: #fff; border-radius: 4px; }
.loading-placeholder { height: 300px; display: flex; align-items: center; justify-content: center; font-size: 16px; color: #909399; }
:deep(.el-table th.el-table__cell) { background-color: #fafafa !important; color: rgba(0, 0, 0, 0.85); font-weight: 500; }
:deep(.el-table td.el-table__cell) { padding: 12px 0; color: rgba(0, 0, 0, 0.65); }
:deep(.el-table .group-name-column .cell) { font-weight: 500; color: #303133; }
.member-list { display: flex; flex-wrap: wrap; gap: 4px; }
.status-tag { display: inline-block; padding: 2px 10px; border-radius: 12px; font-size: 12px; text-align: center; border: 1px solid transparent; }
.status-enabled { background-color: #e6f7ff; border-color: #91d5ff; color: #1890ff; }
.status-disabled { background-color: #fff1f0; border-color: #ffccc7; color: #f5222d; }
.action-button { border-radius: 4px; border: 1px solid; margin-left: 8px; }
.action-button:first-child { margin-left: 0; }
.action-edit { background-color: #fafafa; color: rgba(0, 0, 0, 0.85); border-color: #d9d9d9; }
.action-edit:hover { color: #40a9ff; border-color: #40a9ff; }
.action-enable { background-color: #f6ffed; color: #52c41a; border-color: #b7eb8f; }
.action-enable:hover { background-color: #d9f7be; }
.action-disable { background-color: #fff1f0; color: #f56c6c; border-color: #fbc4c4; }
.action-disable:hover { background-color: #fef0f0; }
.pagination-container { display: flex; justify-content: space-between; align-items: center; margin-top: 24px; padding: 0 20px; }
.pagination-summary { color: rgba(0, 0, 0, 0.65); font-size: 14px; }
:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) { background-color: #1890ff; }
:deep(.el-pagination.is-background .el-pager li:not(.is-disabled):hover) { color: #1890ff; }
.create-group-dialog { padding: 10px; }
.form-item { margin-bottom: 24px; }
.form-item h3 { margin-bottom: 12px; color: #303133; font-size: 16px; font-weight: 600; }
.selection-container { display: flex; gap: 16px; height: 300px; }
.selection-panel { flex: 1; display: flex; flex-direction: column; border: 1px solid #ebeef5; border-radius: 4px; overflow: hidden; }
.selection-panel h4 { padding: 10px 12px; margin: 0; background-color: #f5f7fa; color: #606266; font-size: 14px; font-weight: 500; border-bottom: 1px solid #ebeef5; }
.search-box { padding: 8px; border-bottom: 1px solid #ebeef5; }
.option-list, .selected-list { flex: 1; overflow-y: auto; padding: 8px; }
.option-item { display: block; padding: 8px; margin: 4px 0; border-radius: 4px; }
.option-item:hover { background-color: #f5f7fa; }
.selected-item { position: relative; padding: 8px 28px 8px 12px; margin: 4px 0; background-color: #f0f7ff; border-radius: 4px; border: 1px solid #c6e2ff; }
.remove-icon { position: absolute; right: 8px; top: 50%; transform: translateY(-50%); cursor: pointer; color: #999; font-size: 12px; }
.remove-icon:hover { color: #f56c6c; }
.empty-hint { color: #909399; text-align: center; padding: 20px 0; font-size: 14px; }

/* 【新增】查看对话框的样式 */
.view-group-dialog { padding: 10px; }
.view-item { display: flex; align-items: flex-start; margin-bottom: 18px; font-size: 14px; }
.view-item-vertical { flex-direction: column; align-items: flex-start; }
.view-label { width: 120px; color: #606266; font-weight: 600; text-align: right; padding-right: 12px; flex-shrink: 0; }
.view-item-vertical .view-label { text-align: left; margin-bottom: 8px; }
.view-content { color: #303133; flex-grow: 1; }
.view-member-list { padding: 10px; background-color: #f9f9f9; border-radius: 4px; width: 100%; box-sizing: border-box; line-height: 1.8; }
.member-tag {
  /* 可以根据需要设置样式，例如用标签形式展示 */
}
</style>
